﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConfeccionesJR.Entites;
using System.Data;
using System.Data.Objects;

namespace ConfeccionesJR.Repository
{
    public class DetalleCompraRepository:MasterDataAccess,IDetalleCompraRepository
    {
        public List<DETALLECOMPRA> GetAllFromDetalleCompraByCompraId(int id)
        {
            var query = from c in Context.DETALLECOMPRAs.Include("MATERIAL")
                        where c.CompraId.Equals(id)
                        select c;

            ObjectContext.Refresh(RefreshMode.StoreWins, query);

            return query.ToList();
        }

        public List<DETALLECOMPRA> GetFromDetalleCompraByProductoAndCompraId(string descripcion,Int32 id)
        {
            if (descripcion != "")
            {
                var query = from c in Context.DETALLECOMPRAs.Include("MATERIAL")
                            where (c.MATERIAL.Descripcion.ToUpper().Contains(descripcion.ToUpper())) 
                            & (c.CompraId.Equals(id))
                            select c;

                ObjectContext.Refresh(RefreshMode.StoreWins, query);

                return query.ToList();
            }
            else
            {
                var query = from c in Context.DETALLECOMPRAs.Include("MATERIAL")
                            where c.CompraId.Equals(id)
                            select c;

                ObjectContext.Refresh(RefreshMode.StoreWins, query);

                return query.ToList();
            }
            
        }

        public DETALLECOMPRA GetDetalleCompraByMaterialIdAndCompraId(int idproducto, int idcompra)
        {
            var query = from c in Context.DETALLECOMPRAs
                        where c.materialId.Equals(idproducto) && c.CompraId.Equals(idcompra)
                        select c;

            ObjectContext.Refresh(RefreshMode.StoreWins, query);

            return query.SingleOrDefault();
        }

        public bool GetAllDetallesCompraByCompraId(int idCompra)
        {
            var query = from c in Context.DETALLECOMPRAs.Include("COMPRA")
                        where c.CompraId.Equals(idCompra)
                        select c;
            
            ObjectContext.Refresh(RefreshMode.StoreWins, query);
            
            return query.Any();
        }

        public void RemoveDetalleCompraByMaterialIdAndCompraId(int idProd, int idCompra)
        {
            var existe = Context.DETALLECOMPRAs.Where(c => c.CompraId.Equals(idCompra) 
                && c.MATERIAL.Id.Equals(idProd)).SingleOrDefault();
            Context.DETALLECOMPRAs.Remove(existe);
            Context.SaveChanges();
        }
    }
}
